package com.omesoft.hksnore.util.photo;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.os.Environment;
import android.util.Log;

import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.dbhelper.SoftParam;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class SettingUtil {
    /**
     * 页数
     */
    public static int PAGE = 1;
    /**
     * 条数
     */
    public static int ROW = 30;
    public static String frequencyFileName = "";
    public static String bleName = "";
    public static String bleNameHis = "";
    public final static int BLE_NO_OPEN = 10001;
    public final static int BLE_CONNECTED = 10002;
    public final static int BLE_SEACH = 10003;
    public final static int BLE_VIBRATION = 10086;
    public final static int BLE_DIS = 10004;
    public final static int BLE_NO_CONNECT = 10005;
    public static boolean isOpenBle = false;
    public static boolean isOpenBle2 = false;
    public static boolean isRegistered = false;


    public final static int MAXCOUNT = 10;
    public final static int MAXCOUNT2 = 100;

    public static boolean isMove = false;

    public static int m_mbBufLen = 0;

    public static boolean isFastForward = false;// 标示是否在拖动进度条
    public static int maxNum = 0;
    public static int num = 2;

    public final static String PROJECTNAME = "enjoyhealth";
    public static String PICTURE_SAVE_PATH = "/omesoft/snorekiller/ask/";
    /**
     * 数据库在SD卡上的存储路径
     */
    public static String DB_SAVE_PATH = "/omesoft/snorekiller/databases/";


    /**
     * 心率上限
     */
    public final static int HR_H = 95;
    /**
     * 心率下限
     */
    public final static int HR_L = 56;
    /**
     * 呼吸率上限
     */
    public final static int BREATHING_H = 40;
    /**
     * 呼吸率下限
     */
    public final static int BREATHING_L = 10;
    /**
     * 间隔时间
     */
    public final static int HTIME = 700;
    /**
     * 呼吸波，下限标准
     */
    public final static int HBREATHING_VALUE = 2500;
    /**
     * 心率系数
     */
    public final static double HR_VALUE = 4.375;
    /**
     * 每次拿的数据长度(真实的数据是折半，有一半的数据是\n)
     */
    public final static int mLineCount = 10;


    /**
     * 存储文件的文件路径
     */
    public static final String TEXT_DIR = Environment
            .getExternalStorageDirectory() + "/omesoft/hksnore/snore";
    public static final String TEXT_RECORD_DIR = Environment
            .getExternalStorageDirectory() + "/omesoft/hksnore/snore/record";

    /**
     * 获取当前时间--格式为：2013-03-03 12:03
     */
    public static String get_Time_Format() {
        /**
         * DateFormat.getDateTimeInstance() 初始化时间--格式为：2013/03/03 12:03:33
         */
        Date date = Calendar.getInstance().getTime();
        int y, mon, d, h, min, s;

        y = (date.getYear() + 1900);
        mon = (date.getMonth() + 1);
        d = (date.getDate());
        h = (date.getHours());
        min = (date.getMinutes());
        // s = (date.getSeconds());
        String time = "" + y + "-" + oneLength_Format(mon) + "-" + oneLength_Format(d) + " " + oneLength_Format(h) + ":"
                + oneLength_Format(min);

        Log.d("test", "Calendar::" + Calendar.SUNDAY);
        Log.d("test", "当前时间::" + time);
        return time;
    }

    public static String oneLength_Format(int time) {
        String formatTime = "" + time;
        if (formatTime.length() == 1) {
            return "0" + formatTime;
        } else {
            return formatTime;
        }
    }


    /**
     * 获取多少（最大為12）個月前的时间--格式为：2013-03-03 12:03:33
     */
    public static String get_StartTime_Format(int monthNum) {
        /**
         * DateFormat.getDateTimeInstance() 初始化时间--格式为：2013/03/03 12:03:33
         */
        Date date = Calendar.getInstance().getTime();
        int y, mon, d, h, min, s;

        y = (date.getYear() + 1900);
        mon = (date.getMonth() + 1);
        d = (date.getDate());
        h = (date.getHours());
        min = (date.getMinutes());
        s = (date.getSeconds());
        // 計算N個月前的年月日（最大為12）
        if ((mon - monthNum) <= 0) {
            mon = mon + 12 - monthNum;
            y = y - 1;
        } else {
            mon = mon - monthNum;
        }
        if (d > 28)
            d = 28;
        String time = "" + y + "-" + oneLength_Format(mon) + "-"
                + oneLength_Format(d) + " " + oneLength_Format(h) + ":"
                + oneLength_Format(min) + ":" + oneLength_Format(s);
//		//System.out.println("当前时间："+time);
        return time;
    }

    /**
     * 健康状况选中类型
     */
    private static int healthStatusType;
    /**
     * 健康状况选中内容
     */
    private static String healthStatusContent;

    private static String lifeStyleContent;

    /**
     * 是否第一次运行
     */
    private static boolean isFirstRun;

    public final static String INITRECORDUSERID = "InitRecordUserId";

    /**
     * 获取图片保存路径
     */
    public static String getPICTURE_SAVE_PATH(Context mContext) {
        SharedPreferences sp = getProjectSP(mContext);
        SettingUtil.PICTURE_SAVE_PATH = sp.getString("PICTURE_SAVE_PATH", PICTURE_SAVE_PATH);
        return PICTURE_SAVE_PATH;
    }

    /**
     * 设置图片保存路径
     */
    public static void setPICTURE_SAVE_PATH(Context mContext, String PICTURE_SAVE_PATH) {
        SharedPreferences sp = getProjectSP(mContext);
        Editor editor = sp.edit();
        editor.putString("PICTURE_SAVE_PATH", PICTURE_SAVE_PATH).commit();
    }

    /**
     * 获取当前项目的偏好设置
     */
    public static SharedPreferences getProjectSP(Context context) {
        return context.getSharedPreferences(PROJECTNAME, Context.MODE_PRIVATE);
    }

    /**
     * 获取SDCard中db目录
     */
    public static String getSDCardDatabasesPath() {
        String databasesPath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + DB_SAVE_PATH;
        return databasesPath;
    }

    /**
     * 获取手机中db目录
     */
    public static String getPhoneDatabasesPath() {
        String databasesPath = Environment.getDataDirectory()// 设置数据库的路径
                .getAbsolutePath() + DB_SAVE_PATH;
        return databasesPath;
    }

    /**
     * 获取DB保存路径
     */
    public static String getDB_SAVE_PATH(Context mContext) {
        SharedPreferences sp = getProjectSP(mContext);
        SettingUtil.DB_SAVE_PATH = sp.getString("DB_SAVE_PATH", getPhoneDatabasesPath());
        return SettingUtil.DB_SAVE_PATH;
    }

    /**
     * 设置DB保存路径
     */
    public static void setDB_SAVE_PATH(Context mContext, String DB_SAVE_PATH) {
        SharedPreferences sp = getProjectSP(mContext);
        Editor editor = sp.edit();
        // Log.v("test", "DB_SAVE_PATH:"+DB_SAVE_PATH);
        editor.putString("DB_SAVE_PATH", DB_SAVE_PATH).commit();
    }

    /**
     * 判断是否初始化了问答模块(主要数据库)
     */
    public static boolean isInitAskModule(Context mContext) {
        SharedPreferences sp = getProjectSP(mContext);
        boolean init_ask = sp.getBoolean("init_ask", false);
        return init_ask;
    }

    /**
     * 设置已经初始化了问答模块(主要数据库)
     */
    public static void setInitAskModule(Context mContext, boolean init_ask) {
        SharedPreferences sp = getProjectSP(mContext);
        Editor editor = sp.edit();
        editor.putBoolean("init_ask", init_ask).commit();
    }

    public static int getHealthStatusType(Context mContext, int userId) {
        SharedPreferences sp = getProjectSP(mContext);
        int healthStatusType = sp.getInt("healthStatusType" + userId, -1);
        return healthStatusType;
    }

    public static void setHealthStatusType(Context mContext, int healthStatusType, int userId) {
        SharedPreferences sp = getProjectSP(mContext);
        Editor editor = sp.edit();
        editor.putInt("healthStatusType" + userId, healthStatusType).commit();
    }

    public static String getHealthStatusContent(Context mContext, int userId) {
        SharedPreferences sp = getProjectSP(mContext);
        String healthStatusContent = sp.getString("healthStatusContent" + userId, "");
        return healthStatusContent;
    }

    public static void setHealthStatusContent(Context mContext, String healthStatusContent, int userId) {
        SharedPreferences sp = getProjectSP(mContext);
        Editor editor = sp.edit();
        editor.putString("healthStatusContent" + userId, healthStatusContent).commit();
    }

    public static String getLifeStyleContent(Context mContext, int userId) {
        SharedPreferences sp = getProjectSP(mContext);
        String healthStatusContent = sp.getString("lifeStyleContent" + userId, "");
        return healthStatusContent;
    }

    public static void setLifeStyleContent(Context mContext, String healthStatusContent, int userId) {
        SharedPreferences sp = getProjectSP(mContext);
        Editor editor = sp.edit();
        editor.putString("lifeStyleContent" + userId, healthStatusContent).commit();
    }

    public static boolean isFirstRun(String version, Context mContext) {
        SharedPreferences sp = getProjectSP(mContext);
        boolean healthStatusContent = sp.getBoolean(version + "isFirstRun", true);
        return healthStatusContent;
    }

    public static void setFirstRun(Context mContext, String version, boolean isFirstRun) {
        SharedPreferences sp = getProjectSP(mContext);
        Editor editor = sp.edit();
        editor.putBoolean(version + "isFirstRun", isFirstRun).commit();
    }

    /**
     * 该版本是否已经初始化了
     */
    public static boolean isInitVersion(Context context) {
        SharedPreferences sp = getProjectSP(context);
        return sp.getBoolean(SoftParam.getStrByVersionCode_VersionName(context), false);
    }

    /**
     * 标识该版本已经初始化了
     */
    public static void setInitVersion(Context context) {
        SharedPreferences sp = getProjectSP(context);
        Editor editor = sp.edit();
        editor.putBoolean(SoftParam.getStrByVersionCode_VersionName(context), true).commit();
    }

    public static final String PICSAVESIZE = "picSaveSize";

    /***
     * 设置图片存放大小偏好
     *
     * @param context
     * @return
     */
    public static void setPicSaveSize(Context context, int picSaveSize) {
        Editor editor = SettingUtil.getProjectSP(context).edit();
        editor.putInt(PICSAVESIZE, picSaveSize).commit();
    }

    /***
     * 获取图片存放大小偏好
     *
     * @param context
     * @return
     */
    public static int getPicSaveSize(Context context) {
        return SettingUtil.getProjectSP(context).getInt(PICSAVESIZE, 3);
    }

    public static final String ASKTOPICJSON = "askTopicJson";

    /**
     * 问答话题的json
     *
     * @param context
     * @param
     */
    public static void setAskTopicJson(Context context, String askTopicJson) {
        Editor editor = SettingUtil.getProjectSP(context).edit();
        editor.putString(ASKTOPICJSON, askTopicJson).commit();
    }

    public static String getAskTopicJson(Context context) {
        return SettingUtil.getProjectSP(context).getString(ASKTOPICJSON, "");
    }

    public static final String ISHASUPDATEASKTOPICJSON = "isHasUpdateAskTopicJson";

    /**
     * 是否有更新问答话题的json
     *
     * @param context
     * @param isHasUpdateAskTopicJson
     */
    public static void setIsHasUpdateAskTopicJson(Context context, boolean isHasUpdateAskTopicJson) {
        Log.d("test", "setIsHasUpdateAskTopicJson");
        Editor editor = SettingUtil.getProjectSP(context).edit();
        editor.putBoolean(ISHASUPDATEASKTOPICJSON, isHasUpdateAskTopicJson).commit();
    }

    public static boolean isHasUpdateAskTopicJson(Context context) {
        Log.d("test", "isHasUpdateAskTopicJson");
        return SettingUtil.getProjectSP(context).getBoolean(ISHASUPDATEASKTOPICJSON, false);
    }

    public static final String ISWIFISYNC = "isWifiSync";

    public static void setIsWifiSync(Context context, boolean isWifiSync) {
        Editor editor = SettingUtil.getProjectSP(context).edit();
        editor.putBoolean(ISWIFISYNC, isWifiSync).commit();
    }

    public static boolean isWifiSync(Context context) {
        return SettingUtil.getProjectSP(context).getBoolean(ISWIFISYNC, false);
    }

    public static final String ISSAVEPIC = "isSavePic";

    public static void setIsSavePic(Context context, boolean isSavePic) {
        Editor editor = SettingUtil.getProjectSP(context).edit();
        editor.putBoolean(ISSAVEPIC, isSavePic).commit();
    }

    public static boolean isSavePic(Context context) {
        return SettingUtil.getProjectSP(context).getBoolean(ISSAVEPIC, false);
    }

    public static final String ISPN_MSG = "isPN_Msg";

    public static void setIsPN_Msg(Context context, boolean isSavePic) {
        Editor editor = SettingUtil.getProjectSP(context).edit();
        editor.putBoolean(ISPN_MSG, isSavePic).commit();
    }

    public static boolean isPN_Msg(Context context) {
        return SettingUtil.getProjectSP(context).getBoolean(ISPN_MSG, false);
    }

    /**
     * 保存该当前的记录用户id
     */
    public static void setInitRecordUserId(Context context, int recordUserId) {
        SharedPreferences sp = getProjectSP(context);
        Editor editor = sp.edit();
        editor.putInt(INITRECORDUSERID, recordUserId).commit();
    }

    /**
     * 获取该当前的记录用户id
     */
    public static Integer getInitRecordUserId(Context context) {
        SharedPreferences sp = getProjectSP(context);
        return sp.getInt(INITRECORDUSERID, 1);
    }

    /**
     * 判断是否是平板手机
     *
     * @param context
     * @return
     */
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 获取时长
     *
     * @param context
     * @param beginTime
     * @param endTime
     * @return
     */
    public static String getTimeDifference(Context context, long beginTime,
                                           long endTime) throws ParseException {
        Date start = null;
        Date end = null;
        String text = "";
        start = new Date(beginTime);
        start = new Date(endTime);

        long between = endTime - beginTime;// 得到两者的毫秒数
        long day = between / (24 * 60 * 60 * 1000);
        long hour = (between / (60 * 60 * 1000) - day * 24);
        long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000
                - min * 60 * 1000 - s * 1000);
        String tempDay = "";
        String tempHour = "";
        String tempMinute = "";
        String tempSecond = "";
        String tempMills = "";
        if (day < 10) {
            tempDay = "0" + day;
        } else {
            tempDay = "" + day;
        }
        tempDay = tempDay + " "
                + context.getResources().getString(R.string.snore_his_date);
        if (hour < 10) {
            tempHour = "0" + hour;
        } else {
            tempHour = "" + hour;
        }
        tempHour = tempHour + ""
                + ":";
        if (min < 10) {
            tempMinute = "0" + min;
        } else {
            tempMinute = "" + min;
        }
        tempMinute = tempMinute + ""
                + ":";
        if (s < 10) {
            tempSecond = "0" + s;
        } else {
            tempSecond = "" + s;
        }
        tempSecond = tempSecond + ""
                + "";
        if (ms < 10) {
            tempMills = "00" + ms;
        } else if (ms < 100) {
            tempMills = "0" + ms;
        } else {
            tempMills = "" + ms;
        }
        tempMills = tempMills + " "
                + context.getResources().getString(R.string.snore_his_mills);
        // text =
        // context.getResources().getString(R.string.his_breathing_test_time)+" "
        // + tempDay + " "
        // + tempHour + " " + tempMinute + " " + tempSecond + " " + tempMills;
        text = tempHour + "" + tempMinute + "" + tempSecond;
        return text;
    }

    public static String[][] ReadTxtFile(Context context, String strFilePath) {
        String path = strFilePath;
        String[][] str = new String[1][3];
        // 打开文件
        File file = new File(path);
        // 如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory()) {
            Log.e("TestFile", "The File doesn't not exist.");
        } else {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(
                            instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    // 分行读取
                    List<String> lis = new ArrayList<String>();
                    while ((line = buffreader.readLine()) != null) {
                        if (line.length() > 0) {
                            lis.add(line);
                        }
                    }
                    String[] str1 = lis.get(0).split(",");
                    String[] str2 = lis.get(lis.size() - 1).split(",");

                    String str3 = getDistanceTime(context, str1[0], str2[0]);
                    str[0][0] = str1[0];
                    str[0][1] = str3;
                    str[0][2] = str2[0];

                    instream.close();
                }
            } catch (java.io.FileNotFoundException e) {
                e.printStackTrace();
                Log.e("TestFile", "The File doesn't not exist.");
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("TestFile", e.getMessage());
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        return str;
    }


    /***
     * @param startTime 最大时间
     * @param currTime  当前进度时间
     */
    public static String getTestTime(Context context, String currTime, String startTime) {
        Date start = null;
        Date curr = null;
        String text = "";
        try {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            start = sd.parse(startTime);
            curr = sd.parse(currTime);
            long between = (curr.getTime() - start.getTime());// 得到两者的毫秒数

            long day = between / (24 * 60 * 60 * 1000);
            long hour = (between / (60 * 60 * 1000) - day * 24);
            long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

            String tempHour = "";
            String tempMinute = "";
            String tempSecond = "";
            if (hour < 10) {
                tempHour = "0" + hour;
            } else {
                tempHour = "" + hour;
            }
            tempHour = tempHour
                    + "";
            if (min < 10) {
                tempMinute = "0" + min;
            } else {
                tempMinute = "" + min;
            }
            tempMinute = tempMinute
                    + "";
            if (s < 10) {
                tempSecond = "0" + s;
            } else {
                tempSecond = "" + s;
            }
            tempSecond = tempSecond
                    + "";

            text = tempHour + ":" + tempMinute + ":" + tempSecond;
        } catch (ParseException e) {
            e.printStackTrace();
            text = "00:00:00";
            return text;

        }
        return text;
    }


    public static String getDistanceTime(Context context, String str1,
                                         String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        String days = "";
        Log.e("xx", "str1 " + str1);
        Log.e("xx", "str2 " + str2);
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            // if (time1 < time2) {

            diff = time2 - time1;
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
            Log.e("xx", "day " + day + "  hour " + hour + "  min " + min
                    + "  sec " + sec);

            String _day = day < 10 ? "0" + day : day + "";
            String _hour = hour < 10 ? "0" + hour : hour + "";
            String _min = min < 10 ? "0" + min : min + "";
            String _sec = sec < 10 ? "0" + sec : sec + "";


            if (day == 0) {
                if (hour == 0) {
                    days = "00:" + _min + ":" + _sec;
                } else if (min == 0) {
                    days = "00:" + "00:" + _sec;
                } else {
                    days = _hour + ":" + _min + ":" + _sec;
                }
            } else {
                days = _day
                        + context.getResources().getString(
                        R.string.snore_main_day);
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 判断字符串是否为日期格式
     *
     * @param date
     * @return
     */
    public static boolean isDateStringValid(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 输入对象不为空
        try {
            sdf.parse(date);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
}
